package com.tuanchau.android.englishtooltip.database;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLProcess {
	private static DocumentBuilderFactory dbf = null;
	private static DocumentBuilder db = null;
	private static Document doc;

	public static ScaleWord[] parseWordFromXml(String xmlString) {
		try {
			if (dbf == null) {
				dbf = DocumentBuilderFactory.newInstance();
				db = dbf.newDocumentBuilder();
			}
//			xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
//					+ xmlString;
			ByteArrayInputStream bis = null;
			try {
				bis = new ByteArrayInputStream(xmlString.getBytes("UTF-8"));
			} catch (UnsupportedEncodingException e) {
				bis = new ByteArrayInputStream(xmlString.getBytes("UTF8"));
			}

			doc = db.parse(bis);

			NodeList nl = doc.getChildNodes();
			final Node root = nl.item(0);
			Node nodeSize = getNode(root, "count");
			int size = Integer.parseInt(nodeSize.getTextContent());
			if (size == 0)
				return null;
			ScaleWord[] result = new ScaleWord[size];

			nl = ((Element) root).getElementsByTagName("e");

			for (int i = 0; i < size; i++) {
				result[i] = readNode(nl.item(i));
			}

			return result;
		} catch (Exception e) {
			return null;
		}
	}

	private static ScaleWord readNode(final Node node) {
		return new ScaleWord(getNode(node, "t").getTextContent(),getNode(node, "m").getTextContent().trim());
	}

	private static String formatMean(String mean) {
		if (mean.startsWith("(")) {
			int countOpen = 1;
			char[] arr = mean.toCharArray();
			int length = arr.length;
			int i = 1;
			String left = "(";
			for (i = 1; i < length && countOpen > 0; i++) {
				if (arr[i] == '(') {
					countOpen++;

				} else if (arr[i] == ')') {
					countOpen--;
				}
				left += arr[i];

			}
			String right = "";
			if (i < length)
				right = mean.substring(i).trim();
			return right + " " + left;
		} else {
			return mean;
		}

	}

	private static Node getNode(Node parent, String nodeName, int position) {
		return ((Element) parent).getElementsByTagName(nodeName).item(position);
	}

	private static Node getNode(Node parent, String nodeName) {
		NodeList nl = ((Element) parent).getElementsByTagName(nodeName);
		return nl.item(0);
	}

}
